package com.jessefyz.module.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jessefyz.module.shop.constants.CouponConstant;
import com.jessefyz.module.shop.domain.LitemallCoupon;
import com.jessefyz.module.shop.domain.LitemallCouponUser;
import com.jessefyz.module.shop.service.ILitemallCouponService;
import com.jessefyz.module.shop.service.ILitemallCouponUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CouponAssignService {

    @Autowired
    private ILitemallCouponUserService couponUserService;
    @Autowired
    private ILitemallCouponService couponService;

    /**
     * 分发注册优惠券
     *
     * @param userId
     * @return
     */
    public void assignForRegister(Long userId) {
        List<LitemallCoupon> couponList = couponService.list(
                new LambdaQueryWrapper<LitemallCoupon>()
                .eq(LitemallCoupon::getType, CouponConstant.TYPE_REGISTER)
                .eq(LitemallCoupon::getStatus, CouponConstant.STATUS_NORMAL)
        );
        Date now = new Date();
        for(LitemallCoupon coupon : couponList){
            Long couponId = coupon.getId();

            Integer count = couponUserService.count(
                    new LambdaQueryWrapper<LitemallCouponUser>()
                    .eq(LitemallCouponUser::getUserId,userId)
                    .eq(LitemallCouponUser::getCouponId,couponId)
            );
            if (count > 0) {
                continue;
            }
            Integer limit = coupon.getLimit();
            while(limit > 0){
                LitemallCouponUser couponUser = new LitemallCouponUser();
                couponUser.setCouponId(couponId);
                couponUser.setUserId(userId);
                Integer timeType = coupon.getTimeType();
                if (timeType.equals(CouponConstant.TIME_TYPE_TIME)) {
                    couponUser.setStartTime(coupon.getStartTime());
                    couponUser.setEndTime(coupon.getEndTime());
                }
                else{
                    couponUser.setStartTime(now);
                    couponUser.setEndTime(DateUtil.offset(now, DateField.DAY_OF_MONTH, coupon.getDays()));
                }
                couponUser.setAddTime(new Date());
                couponUser.setUpdateTime(new Date());
                couponUserService.save(couponUser);

                limit--;
            }
        }

    }

}
